

from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.mixins import UpdateModelMixin
from meiduo_admin.serializers.order_serializers import *
from meiduo_admin.utils.pages import MyPage

from rest_framework.permissions import IsAdminUser,BasePermission

# 自定义权限类
class ModifyOrderInfo(BasePermission):

    def has_permission(self, request, view):
        # 判断用户是否有操作OrderInfo的权限
        user = request.user
        if user.is_anonymous:
            return False

        return user.has_perms(['orders.add_orderinfo', 'orders.change_orderinfo', 'orders.delete_orderinfo'])


class OrderAPIView(UpdateModelMixin, ReadOnlyModelViewSet):

    queryset = OrderInfo.objects.all()
    serializer_class = OrderSimpleSerializer

    pagination_class = MyPage

    permission_classes = [
        IsAdminUser,
        # 自定义权限验证，必须拥有对OrderInfo增删改的权限才能够访问
        # ModifyOrderInfo
    ]


    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(order_id__contains=keyword)

        return self.queryset.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return self.serializer_class
        elif self.action == 'retrieve':
            return OrderDetailSerializer
        elif self.action == 'partial_update':
            return OrderDetailSerializer